import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class Notifications {
  // 工厂模式
  factory Notifications() => _getInstance();

  static Notifications get instance => _getInstance();
  static Notifications _instance;
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  BuildContext context;

  Notifications._internal() {
    // 初始化
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: onSelectNotification);

  }

  static Notifications _getInstance() {
    if (_instance == null) {
      _instance = new Notifications._internal();
    }
    return _instance;
  }

  void setContext(BuildContext context){
    this.context=context;
  }

  /**
   * 点击通知栏的事件
   */
  Future onSelectNotification(String payload) {
    debugPrint("payload : $payload");
    showDialog(
      context: context,
      builder: (_) => new AlertDialog(
        title: new Text('Notification'),
        content: new Text('$payload'),
      ),
    );
  }

  /**
   * 添加消息
   */
  show(String name,String title) async {
    var android = new AndroidNotificationDetails(
        'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
        priority: Priority.High,importance: Importance.Max
    );
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
        0, name, title, platform,
        payload: 'Nitish Kumar Singh is part time Youtuber');
  }

  void cancel(int channel_id) async {
    //参数 大于0 为需要删除的通知的id，否则是全部删除
    if(channel_id>0){
      await flutterLocalNotificationsPlugin.cancel(channel_id);
    }else{
      await flutterLocalNotificationsPlugin.cancelAll();
    }
  }

}